package com.software.loginregister.fragment.homecategoryfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.software.loginregister.R;
import com.software.loginregister.adapter.RecommendAdapter;
import com.software.loginregister.databasesHelper.AppDatabase;
import com.software.loginregister.databasesHelper.WorksCacheDao;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.room.WorksCache;
import com.software.loginregister.entity.vo.WorksDTO;
import com.software.loginregister.util.CameraUtils;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecommendFragment extends Fragment {
    private static final String TAG = "RecommendFragment";
    private static final int PAGE_SIZE = 20;
    private static final long CACHE_EXPIRY_TIME = 5 * 60 * 1000; // 5分钟缓存过期

    private RecyclerView rvRecommend;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<WorksDTO> worksList;
    private RecommendAdapter recommedAdapter;
    private CameraUtils cameraUtils;
    private CardView cvCamera;
    private int currentPage = 1;
    private boolean isLoading = false;
    private boolean isRefreshing = false;
    private final Executor executor = Executors.newSingleThreadExecutor();
    private WorksCacheDao worksCacheDao;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, container, false);
        cameraUtils = new CameraUtils(this);
        worksCacheDao = AppDatabase.getDatabase(requireContext()).worksCacheDao();
        initView(view);
        loadRecipeData(false);
        return view;
    }

    private void initView(View view) {
        // 相机按钮初始化
        cvCamera = view.findViewById(R.id.cv_camera);
        cvCamera.setOnClickListener(v -> {
            // 修改这里的调用方式
            if (cameraUtils != null) {
                Log.d(TAG, "Showing camera dialog from RecommendFragment");
                // 确保在 Fragment 的上下文中调用
                if (isAdded() && getActivity() != null) {
                    cameraUtils.showCameraDialog();
                } else {
                    Log.e(TAG, "Fragment not attached or activity is null");
                }
            } else {
                Log.e(TAG, "CameraUtils is null");
            }
        });

        // 下拉刷新初始化
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.theme_color);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            isRefreshing = true;
            currentPage = 1;
            loadRecipeData(true);
        });

        // RecyclerView初始化
        rvRecommend = view.findViewById(R.id.rv_recommend);
        GridLayoutManager layoutManager = new GridLayoutManager(requireContext(), 2);
        rvRecommend.setLayoutManager(layoutManager);
        worksList = new ArrayList<>();
        recommedAdapter = new RecommendAdapter(requireContext(), worksList);
        rvRecommend.setAdapter(recommedAdapter);

        // 设置滚动加载更多
        rvRecommend.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (!isLoading && dy > 0) {
                    GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                    if (layoutManager != null) {
                        int visibleItemCount = layoutManager.getChildCount();
                        int totalItemCount = layoutManager.getItemCount();
                        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

                        if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount) {
                            currentPage++;
                            loadRecipeData(true);
                        }
                    }
                }
            }
        });
    }

    private void loadRecipeData(Boolean forceRefresh) {
        if (isLoading) return;
        isLoading = true;

        // 如果是第一页且不是强制刷新，先尝试从缓存加载
        if (currentPage == 1 && !forceRefresh) {
            loadFromCache();
        } else {
            loadFromNetwork();
        }
    }

    private void loadFromCache() {
        executor.execute(() -> {
            try {
                List<WorksCache> cacheList = worksCacheDao.getAllWorks();
                if (!cacheList.isEmpty()) {
                    // 检查缓存是否过期
                    long currentTime = System.currentTimeMillis();
                    WorksCache latestCache = cacheList.get(0);
                    if (currentTime - latestCache.getTimestamp() > CACHE_EXPIRY_TIME) {
                        loadFromNetwork();
                        return;
                    }

                    // 转换缓存数据
                    List<WorksDTO> cachedWorks = new ArrayList<>();
                    Gson gson = new Gson();
                    for (WorksCache cache : cacheList) {
                        WorksDTO work = gson.fromJson(cache.getCacheData(), WorksDTO.class);
                        cachedWorks.add(work);
                    }

                    // 在主线程更新UI
                    new Handler(Looper.getMainLooper()).post(() -> {
                        worksList.clear();
                        worksList.addAll(cachedWorks);
                        recommedAdapter.notifyDataSetChanged();
                        isLoading = false;
                        swipeRefreshLayout.setRefreshing(false);
                    });
                } else {
                    loadFromNetwork();
                }
            } catch (Exception e) {
                Log.e(TAG, "加载缓存失败", e);
                loadFromNetwork();
            }
        });
    }

    private void loadFromNetwork() {
        Long userId = SharedPreferencesUtil.getUserId(getContext());
        Log.d(TAG, "加载推荐 - userId: " + userId + ", limit: " + PAGE_SIZE);

        RetrofitClient.getInstance()
                .getWorksApi()
                .getRecommendedWorks(userId, PAGE_SIZE)  // 移除isRefreshing参数
                .enqueue(new Callback<Result<List<WorksDTO>>>() {
                    @Override
                    public void onResponse(@NonNull Call<Result<List<WorksDTO>>> call,
                                           @NonNull Response<Result<List<WorksDTO>>> response) {
                        if (!isAdded()) return;

                        if (response.isSuccessful() && response.body() != null) {
                            Result<List<WorksDTO>> result = response.body();

                            if (result.getCode() == 1 && result.getData() != null) {
                                List<WorksDTO> newData = result.getData();

                                // 打印返回的数据以便调试
                                for (WorksDTO work : newData) {
                                    Log.d(TAG, String.format("\n作品详情 =================" +
                                                    "\n作品ID: %d" +
                                                    "\n标题: %s" +
                                                    "\n作者: %s" +
                                                    "\n难度: %s" +
                                                    "\nphotoUrl: %s" +
                                                    "\n点赞数: %d" +
                                                    "\n推荐分数: %.2f" +
                                                    "\n推荐标签: %s" +
                                                    "\n=================",
                                            work.getWorksId(),
                                            work.getWorksName(),
                                            work.getNickname(),
                                            work.getDifficulty(),
                                            work.getPhotoUrl(),
                                            work.getLikeCount(),
                                            work.getScore(),
                                            work.getReasonTags()
                                    ));
                                }

                                if (currentPage == 1 || isRefreshing) {
                                    worksList.clear();
                                    saveToCache(newData);
                                }
                                worksList.addAll(newData);
                                recommedAdapter.notifyDataSetChanged();
                            }
                        }

                        isLoading = false;
                        isRefreshing = false;
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(@NonNull Call<Result<List<WorksDTO>>> call,
                                          @NonNull Throwable t) {
                        if (!isAdded()) return;
                        Log.e(TAG, "网络请求异常", t);

                        isLoading = false;
                        isRefreshing = false;
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private void saveToCache(List<WorksDTO> works) {
        executor.execute(() -> {
            try {
                // 如果是第一页，清除旧缓存
                if (currentPage == 1) {
                    worksCacheDao.deleteAll();
                }

                // 准备新的缓存数据
                List<WorksCache> cacheList = new ArrayList<>();
                long currentTime = System.currentTimeMillis();
                Gson gson = new Gson();

                for (WorksDTO work : works) {
                    WorksCache cache = new WorksCache();
                    cache.setWorksId(work.getWorksId());
                    cache.setCacheData(gson.toJson(work));
                    cache.setTimestamp(currentTime);
                    cacheList.add(cache);
                }

                // 批量插入缓存
                if (!cacheList.isEmpty()) {
                    worksCacheDao.insertAll(cacheList);
                }
            } catch (Exception e) {
                Log.e(TAG, "保存缓存失败", e);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 添加这个方法来处理相机/图库返回的结果
        if (cameraUtils != null) {
            cameraUtils.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 添加这个方法来处理权限请求的结果
        if (cameraUtils != null) {
            cameraUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
